package cn.inbot.shopadmin.module;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.permissionx.guolindev.PermissionX;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import cn.inbot.shopadmin.R;
import cn.inbot.shopadmin.app.RouterUrls;
import cn.inbot.shopadmin.module.category.CategoryFragment;
import cn.inbot.shopadmin.module.mine.view.MineFragment;
import cn.inbot.shopadmin.module.order.view.CreateOrderFragment;
import cn.inbot.shopadmin.module.order.view.OrderFragment;
import cn.inbot.shopadmin.module.robot.view.RobotFragment;
import cn.inbot.lib.framework.EventManager;
import cn.inbot.lib.framework.PBAppEnviroment;
import cn.inbot.lib.framework.annotation.InjectLayout;
import cn.inbot.lib.framework.debug.PBDebugDialog;
import cn.inbot.lib.framework.mvvm.PBActivity;
import cn.inbot.lib.framework.util.AppUtil;
import cn.inbot.lib.widget.NoScrollViewPager;

import static android.provider.Settings.canDrawOverlays;
import static androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;
import static cn.inbot.lib.util.ext.ToastExtKt.showToast;


@Route(path = RouterUrls.DEMO_MAIN)
@InjectLayout(layoutResId = R.layout.activity_main)
public class MainActivity extends PBActivity {

    private static final int REQUEST_CODE = 98;

    private List<Fragment> mFragmentList = new ArrayList();
    private long mBackPressTime = 0L;
//    private Fragment mRobotFragment = RobotFragment.create();
//    private Fragment mCategoryFragment = CategoryFragment.create();
//    private Fragment mMineFragment = MineFragment.create();

    // 派宝小店相关碎片
    private Fragment mOrderFragment = OrderFragment.create();
    private Fragment mCreateOrderFragment = CreateOrderFragment.create();

    private NoScrollViewPager viewPager;
    BottomNavigationView bottomNavigationView;
    TextView tvTestEnviroment;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        viewPager = findViewById(R.id.viewPager);
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        tvTestEnviroment = findViewById(R.id.tvTestEnviroment);

        EventManager.INSTANCE.register(this);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
//                    case R.id.item_navigation_robot:
//                        viewPager.setCurrentItem(0, false);
//                        break;
//                    case R.id.item_navigation_category:
//                        viewPager.setCurrentItem(1, false);
//                        break;
//                    case R.id.item_navigation_mine:
//                        viewPager.setCurrentItem(2, false);
//                        break;
                    case R.id.item_navigation_order:
                        viewPager.setCurrentItem(0, false);
                        break;
                    case R.id.item_navigation_create_order:
                        viewPager.setCurrentItem(1, false);
                        break;
                }
                return true;
            }
        });
        if (!PBAppEnviroment.INSTANCE.isProduct()) {
            tvTestEnviroment.setVisibility(View.VISIBLE);
        }
        setupViewPager();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList)
                        -> scope.showRequestReasonDialog(deniedList, "核心功能是基于这些权限", "确定", "取消"))
                .onForwardToSettings((scope, deniedList)
                        -> scope.showForwardToSettingsDialog(deniedList, "您需要手动在设置中允许必要的权限", "确定", "取消"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        showToast("授权失败");
                    }
                });
    }

    @Override
    protected void onDestroy() {
        EventManager.INSTANCE.unregister(this);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        long now = System.currentTimeMillis();
        if (now - mBackPressTime > 2000) {
            showToast("请再按一次退出应用");
            mBackPressTime = now;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
            PBDebugDialog.Companion.show(getSupportFragmentManager());
        }
    }

    private void setupViewPager() {
//        mFragmentList.add(0, mRobotFragment);
//        mFragmentList.add(1, mCategoryFragment);
//        mFragmentList.add(2, mMineFragment);
        mFragmentList.add(0, mOrderFragment);
        mFragmentList.add(1, mCreateOrderFragment);


        viewPager.setOffscreenPageLimit(mFragmentList.size());
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!canDrawOverlays(this)) {
            new AlertDialog.Builder(this)
                    .setTitle("消息提示")
                    .setMessage("打开调试对话框,需要悬浮窗权限,请前往设置页面开启")
                    .setCancelable(false)
                    .setPositiveButton("确定", (dialog, which) -> {
                        Uri packageURI = Uri.parse("package:" + AppUtil.getPackageName(this));
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, packageURI);
                        startActivityForResult(intent, REQUEST_CODE);
                    }).show();
        } else {
            PBDebugDialog.Companion.show(getSupportFragmentManager());
        }
        return super.onKeyDown(keyCode, event);
    }
}
